package com.qg.wcsopcuaqj.dispatch.configuration;

import com.qg.wcsopcuaqj.business.entity.TWcsRgvAlarm;
import com.qg.wcsopcuaqj.business.service.ITWcsRgvAlarmService;
import com.qg.wcsopcuaqj.opcua.selfunion.UAService;
import com.qg.wcsopcuaqj.taskPool.RGVHeartRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

import static com.qg.wcsopcuaqj.taskPool.QGSThreadPool.AGVHeart;

/**
 * @author cx
 * desc: 监听 HeartBeat/AlarmDetect
 * @version 1.0
 * @date 2022/3/15 14:23
 */
@Component
public class DoSchedual {

    @Autowired
    private UAService uaService;

    @Autowired
    private ITWcsRgvAlarmService alarmService;

    private final static Logger logger = LoggerFactory.getLogger(DoSchedual.class);
    // 这个cron表达式代表从0秒开始，每过60秒执行一次。
    @Scheduled(initialDelay=1000, fixedRate=5000)
    public void doSchedualForHeartBeat(){
        System.out.println();
        if(!InitialHeartBeat.getConnectStatus()){
            AGVHeart.shutdownNow();
            logger.info("定时器检测到 心跳连接中断，现在尝试 重启心跳连接");
            alarmCreate();
            //run心跳
            RGVHeartRunnable runnable = new RGVHeartRunnable(uaService,alarmService);
            AGVHeart.submit(runnable);
        }

    }

    @Scheduled(initialDelay=1000, fixedRate=5000)
    public void doSchedualForAlarmDetect(){
        System.out.println();
        if(!InitialHeartBeat.getConnectStatus()){
            AGVHeart.shutdownNow();
            logger.info("定时器检测到 心跳连接中断，现在尝试 重启心跳连接");
            alarmCreate();
            //run心跳
            RGVHeartRunnable runnable = new RGVHeartRunnable(uaService,alarmService);
            AGVHeart.submit(runnable);
        }

    }

    private void alarmCreate(){
        //发出报警
        TWcsRgvAlarm alarm = new TWcsRgvAlarm();
        alarm.setAlarmInfo("定时器检测到 心跳连接中断，现在尝试 重启心跳连接");
        alarm.setIsTaskfinished(-1);
        alarm.setRgvName("-1");
        alarm.setIsSendfinished(-1);
        alarm.setHasGoods(-1);
        alarm.setIsPickfinished(-1);
        alarm.setTaskno("心跳检测定时器");
        alarm.setCreateTime(LocalDateTime.now());
        alarm.setUpdateTime(LocalDateTime.now());
        alarmService.getBaseMapper().insert(alarm);
    }

}
